package cn.sunchis.pvuv.sdk.config;

import javax.servlet.ServletRegistration;

import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * DispatcherServletConfiguration配置激活，扩展默认的DispatcherServlet
 * @Author 许亮
 * @Create 2018-7-5 10:54:58
 * @see org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration.DispatcherServletConfiguration
 */
@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnClass(ServletRegistration.class)
@ConditionalOnProperty(prefix="spring.application", name="pvuv-enabled", havingValue="true")
@EnableConfigurationProperties({WebMvcProperties.class, PvuvServiceConfig.class})
public class PvuvDispatcherServletConfiguration {
	private final WebMvcProperties webMvcProperties;

	public PvuvDispatcherServletConfiguration(WebMvcProperties webMvcProperties) {
		this.webMvcProperties = webMvcProperties;
	}
	
	@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
	public DispatcherServlet dispatcherServlet() {
		DispatcherServlet dispatcherServlet = new PvuvDispatcherServlet();
		dispatcherServlet.setDispatchOptionsRequest(
				this.webMvcProperties.isDispatchOptionsRequest());
		dispatcherServlet.setDispatchTraceRequest(
				this.webMvcProperties.isDispatchTraceRequest());
		dispatcherServlet.setThrowExceptionIfNoHandlerFound(
				this.webMvcProperties.isThrowExceptionIfNoHandlerFound());
		return dispatcherServlet;
	}
	
	@Bean
	@ConditionalOnBean(MultipartResolver.class)
	@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
	public MultipartResolver multipartResolver(MultipartResolver resolver) {
		// Detect if the user has created a MultipartResolver but named it incorrectly
		return resolver;
	}
}
